package org.kehongborui.testcenter.demo;

import org.kehongborui.testcenter.demo.domain.User;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhang peng yang ming
 * @create 2018-06-18 19:19
 */
@RestController
public class Example {
    private Map<String,Object> params = new HashMap<>();

    @RequestMapping("/")
    String home() {
        return "Hello World!";
    }

    /**
     * get 方法测试返回 json 信息
     * @return
     */
    @GetMapping("/json")
    @ResponseBody
    public Object json() {
        params.clear();
        params.put("name", "张彭洋明");
        return params;
    }

    /**
     * rest get 接口从路径中获取参数
     * @param userId
     * @param cityId
     * @return
     */
    @GetMapping("/{user_id}/{city_id}")
    public Object user(@PathVariable("user_id")String userId,
                                    @PathVariable("city_id")String cityId) {

        params.clear();
        params.put("userId", userId);
        params.put("cityId", cityId);

        return params;
    }

    /**
     * get 参数默认值测试
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/v1/page_user")
    public Object pageUser(@RequestParam(defaultValue = "0", name = "page") String page,
                           @RequestParam(defaultValue = "10", name = "size") String size) {
        params.clear();
        params.put("page", page);
        params.put("size", size);

        return params;
    }

    /**
     * bean 对象传参
     * 注意：1.需要指定http头为 content-type为application/json
     *       2.使用body传输数据
     *       3.使用post
     * @param user
     * @return
     */
    @RequestMapping("/v1/save_user")
    public Object user(@RequestBody User user) {
        params.clear();
        params.put("user", user);

        return params;
    }

    /**
     * 获取请求头信息
     * localhost:8080/v1/get_header?id=120
     *
     * @param token
     * @param id
     * @return
     */
    @GetMapping("/v1/get_header")
    public Object getHeader(@RequestHeader("access_token")String token, String id) {
        params.clear();
        params.put("token", token);
        params.put("id", id);

        return params;
    }

    /**
     * 从request中获取参数
     * @param request
     * @return
     */
    @GetMapping("/v1/test_request")
    public Object testRequest(HttpServletRequest request){
        params.clear();
        String id = request.getParameter("id");
        params.put("id", id);
        return params;
    }
}